﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using DevManager.Services;
using DynamicData;

namespace DevManager.ViewModels.Pages;

public class PackageListPageModel : PageModelBase
{
    public string Name { get; set; }
    public List<string> Packages { get; set; }
    public PackageListPageModel(KeyValuePair<string,string> package)
    {
        Packages = GetPackage(package.Value);
        Name = package.Key;
    }
    
    public override string PageName () => $"{Name} 包";
    private List<string> GetPackage(string path)
    {
        var list = new List<string>();
        if (string.IsNullOrEmpty(path)) return list;
        var array = path.Split("=");
        if (array.Length < 2) return list;

        if (array[0] == "Path")
        {
            var user = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
            var p = array[^1].Replace("&u", user);
            var folder = new DirectoryInfo(p);
            var mark = "";
            foreach (var s in folder.GetDirectories().Select(info => info.Name))
            {
                if (s.Contains(mark) && !string.IsNullOrEmpty(mark)) continue;
                list.Add(s);
                mark = s;
            }
        }
        else if (array[0] == "Order")
        {
            // pip list
            var order = array[^1].Split(" ");
            var runner = new CommandRunner(order[0]);
            var result = runner.Run(order[^1]);
            result = result.Replace("\r", "");
            var p = result.Split("\n");
            if (p.Length > 1) p = p[1..];
            list.Add(p.Select(x => x.Split(" ")[0]));
        }

        return list;
    }
}